package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author admin
 * @date 2024/9/18
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     */
    @Override
    public void add(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.add(addressBook);
    }

    /**
     * 返回当前用户所有地址
     */
    @Override
    public List<AddressBook> list() {
        //     用户id
        Long userId = BaseContext.getCurrentId();
        return addressBookMapper.list(userId);
    }

    /**
     * 查询默认地址
     */
    @Override
    public AddressBook getDefault() {
        AddressBook addressBook = AddressBook.builder()
                .isDefault(StatusConstant.ENABLE)
                .userId(BaseContext.getCurrentId())
                .build();
        return addressBookMapper.getAddressBook(addressBook);
    }

    /**
     * 设置默认地址
     */
    @Override
    public void setDefault(AddressBook addressBook) {
    //     设置该用户的所有地址为非默认地址
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateDefaultByUserId(addressBook);
    //     设置当前地址为默认地址
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.update(addressBook);
    }

    /**
     * 修改地址
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id查询地址
     */
    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .build();
        return addressBookMapper.getAddressBook(addressBook);
    }

    /**
     * 删除地址
     */
    @Override
    public void delete(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .build();
        addressBookMapper.delete(addressBook);
    }
}
